import { computed, ref, watch } from 'vue'
import type { GlobalTheme } from 'naive-ui'
import { darkTheme } from 'naive-ui'

export interface ThemeConfig {
  name: string
  label: string
  primaryColor: string
  successColor?: string
  warningColor?: string
  errorColor?: string
  infoColor?: string
  backgroundColor?: string
  backgroundColorSecondary?: string
  textColor?: string
  textColorSecondary?: string
  borderColor?: string
  isDark?: boolean
}

export const presetThemes: ThemeConfig[] = [
  {
    name: 'default',
    label: '默认',
    primaryColor: '#18a058',
  },
  {
    name: 'blue',
    label: '科技蓝',
    primaryColor: '#2080f0',
  },
  {
    name: 'purple',
    label: '优雅紫',
    primaryColor: '#722ed1',
  },
  {
    name: 'green',
    label: '清新绿',
    primaryColor: '#52c41a',
  },
  {
    name: 'orange',
    label: '活力橙',
    primaryColor: '#fa8c16',
  },
  {
    name: 'red',
    label: '热情红',
    primaryColor: '#f5222d',
  },
  {
    name: 'pink',
    label: '温柔粉',
    primaryColor: '#eb2f96',
  },
  {
    name: 'dark',
    label: '炫酷黑',
    primaryColor: '#63e2b7',
    isDark: true,
  }
]

const currentTheme = ref<string>('default')
const customTheme = ref<ThemeConfig | null>(null)

// 从localStorage加载主题设置
const loadTheme = () => {
  if (typeof window !== 'undefined') {
    const savedTheme = localStorage.getItem('theme')
    const savedCustomTheme = localStorage.getItem('customTheme')
    
    if (savedTheme) {
      currentTheme.value = savedTheme
    }
    
    if (savedCustomTheme) {
      try {
        customTheme.value = JSON.parse(savedCustomTheme)
      } catch (e) {
        console.warn('Failed to parse custom theme:', e)
      }
    }
  }
}

// 保存主题设置到localStorage
const saveTheme = () => {
  if (typeof window !== 'undefined') {
    localStorage.setItem('theme', currentTheme.value)
    if (customTheme.value) {
      localStorage.setItem('customTheme', JSON.stringify(customTheme.value))
    }
  }
}

export function useTheme() {
  // 当前主题配置
  const themeConfig = computed(() => {
    if (currentTheme.value === 'custom' && customTheme.value) {
      return customTheme.value
    }
    return presetThemes.find(theme => theme.name === currentTheme.value) || presetThemes[0]
  })

  // Naive UI主题对象
  const naiveTheme = computed<GlobalTheme | null>(() => {
    return themeConfig.value?.isDark ? darkTheme : null
  })

  // 主题覆盖变量
  const themeOverrides = computed(() => {
    const config = themeConfig.value
    if (!config) return {}

    return {
      common: {
        primaryColor: config.primaryColor,
        primaryColorHover: lightenColor(config.primaryColor, 10),
        primaryColorPressed: darkenColor(config.primaryColor, 10),
        primaryColorSuppl: config.primaryColor,
        ...(config.successColor && { successColor: config.successColor }),
        ...(config.warningColor && { warningColor: config.warningColor }),
        ...(config.errorColor && { errorColor: config.errorColor }),
        ...(config.infoColor && { infoColor: config.infoColor }),
      }
    }
  })

  // 设置预设主题
  const setTheme = (themeName: string) => {
    currentTheme.value = themeName
    saveTheme()
  }

  // 设置自定义主题
  const setCustomTheme = (theme: ThemeConfig) => {
    customTheme.value = { ...theme, name: 'custom' }
    currentTheme.value = 'custom'
    saveTheme()
  }

  // 重置为默认主题
  const resetTheme = () => {
    currentTheme.value = 'default'
    customTheme.value = null
    saveTheme()
  }

  // 删除自定义主题
  const deleteCustomTheme = () => {
    customTheme.value = null
    if (typeof window !== 'undefined') {
      localStorage.removeItem('customTheme')
    }
    saveTheme()
  }

  // 监听主题变化，应用到CSS变量
  watch(() => themeConfig.value, (newTheme) => {
    if (newTheme && typeof window !== 'undefined') {
      const root = document.documentElement
      root.style.setProperty('--primary-color', newTheme.primaryColor)
      root.style.setProperty('--primary-color-hover', lightenColor(newTheme.primaryColor, 10))
      root.style.setProperty('--primary-color-pressed', darkenColor(newTheme.primaryColor, 10))
      
      // 设置主题模式
      root.setAttribute('data-theme', newTheme.isDark ? 'dark' : 'light')
      
      // 使用自定义颜色或默认颜色
      if (newTheme.isDark) {
        // 深色模式默认值
        root.style.setProperty('--bg-color', newTheme.backgroundColor || '#1a1a1a')
        root.style.setProperty('--bg-color-secondary', newTheme.backgroundColorSecondary || '#2a2a2a')
        root.style.setProperty('--text-color', newTheme.textColor || '#ffffffe6')
        root.style.setProperty('--text-color-secondary', newTheme.textColorSecondary || '#ffffff9a')
        root.style.setProperty('--border-color', newTheme.borderColor || '#3a3a3a')
      } else {
        // 浅色模式默认值
        root.style.setProperty('--bg-color', newTheme.backgroundColor || '#ffffff')
        root.style.setProperty('--bg-color-secondary', newTheme.backgroundColorSecondary || '#f5f5f5')
        root.style.setProperty('--text-color', newTheme.textColor || '#333333')
        root.style.setProperty('--text-color-secondary', newTheme.textColorSecondary || '#666666')
        root.style.setProperty('--border-color', newTheme.borderColor || '#f0f0f0')
      }
    }
  }, { immediate: true })

  // 初始化
  loadTheme()

  return {
    currentTheme: computed(() => currentTheme.value),
    themeConfig,
    naiveTheme,
    themeOverrides,
    presetThemes,
    customTheme: computed(() => customTheme.value),
    setTheme,
    setCustomTheme,
    resetTheme,
    deleteCustomTheme,
  }
}

// 工具函数：颜色变亮
function lightenColor(color: string, percent: number): string {
  const num = parseInt(color.replace('#', ''), 16)
  const amt = Math.round(2.55 * percent)
  const R = (num >> 16) + amt
  const G = (num >> 8 & 0x00FF) + amt
  const B = (num & 0x0000FF) + amt
  return '#' + (0x1000000 + (R < 255 ? R < 1 ? 0 : R : 255) * 0x10000
    + (G < 255 ? G < 1 ? 0 : G : 255) * 0x100
    + (B < 255 ? B < 1 ? 0 : B : 255))
    .toString(16).slice(1)
}

// 工具函数：颜色变深
function darkenColor(color: string, percent: number): string {
  const num = parseInt(color.replace('#', ''), 16)
  const amt = Math.round(2.55 * percent)
  const R = (num >> 16) - amt
  const G = (num >> 8 & 0x00FF) - amt
  const B = (num & 0x0000FF) - amt
  return '#' + (0x1000000 + (R > 255 ? 255 : R < 0 ? 0 : R) * 0x10000
    + (G > 255 ? 255 : G < 0 ? 0 : G) * 0x100
    + (B > 255 ? 255 : B < 0 ? 0 : B))
    .toString(16).slice(1)
}